import React from 'react'
import { useState,useReducer } from 'react';
// 当状态是对象时,可以像class组件的this.setState({btn1:false})一样，更改状态里的某个属性值
// btnStateSet({btn1:false})

function ajaxFn (arg = 0) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(Array.from({length:arg},(v,i)=>i))
        }, 3000);
    })
    
}

export default function Demo(){
    const {data,loading,run} = useRequest2(ajaxFn,{})
    console.warn('render')
	return (
		<div>
            <button onClick={()=>{run(10)}}>查询</button>
            <div>{loading?'loading...':''}</div>
            {
                data.map(ele => <p>{ele}</p>)
            }
		</div>
    )
}




function useRequest (ajaxFn,options={}) {
    const [{data,loading},dispatch] = useReducer((state,action)=>({...state,...action}),{loading:false,data:[]}) 
    const run = async (arg) => {
        dispatch({loading:true,data:[]})
        let res = await ajaxFn(arg)
        dispatch({loading:false,data:res})
    }
    return {data,loading,run}
}
function useRequest2 (ajaxFn) {
 const [{loading,data},dispatch] = useReducer((state,action)=>({...state,...action}),{data:[],loading:false})
 const run = async (...arg)=> {
    dispatch({loading:true})
    let res = await ajaxFn(...arg)
    dispatch({loading:false,data:res})
 }
 return {loading,data,run}
}